package com.demo.mystudy.ui.socketserver.servercmd

import com.demo.mystudy.socketbean.DownloadFileBean
import com.demo.mystudy.socketbean.MessageWrapper
import com.jetinno.simple.utils.FilePath
import com.jetinno.simple.utils.JsonUtil
import org.java_websocket.WebSocket
import timber.log.Timber
import java.io.File
import java.io.IOException

/**
 * Created by zhangyuncai on 2025/4/28.
 * 描述：
 */
object ServerCmdDownloadFile : ServerCmdInterface {
    private val CHUNK_SIZE = 64 * 1024 // 64KB
    override val cmd: String
        get() = "DownloadFile"

    override fun receive(conn: WebSocket, messageWrapper: MessageWrapper) {
        var bean =
            JsonUtil.jsonToAny(messageWrapper.message, DownloadFileBean::class.java) ?: return
        val file = File(FilePath.EXTERNAL_STORAGE_FILE, bean.filePath)

        var newBean = DownloadFileBean()
        if (!file.exists()) {
            newBean = DownloadFileBean()
            newBean.cmd = bean.cmd
            newBean.errorReason = "机器不存在该文件夹"
            conn.send(JsonUtil.anyToJson(newBean))
            return
        }

        try {
            // 发送文件信息
            newBean = DownloadFileBean()
            newBean.cmd = bean.cmd
            newBean.childCmd = "fileInfo"
            newBean.filePath = bean.filePath
            newBean.fileInfoFileSize = file.length()
            conn.send(JsonUtil.anyToJson(newBean))

            // 分块发送文件
            file.inputStream().use { fis ->
                val buffer = ByteArray(CHUNK_SIZE)
                var bytesRead: Int
                var totalSent = 0L
                while (fis.read(buffer).also { bytesRead = it } != -1) {
                    val chunk =
                        if (bytesRead == CHUNK_SIZE) buffer else buffer.copyOf(bytesRead)
                    totalSent += bytesRead
//                    // 可以发送进度信息（可选）
                    val progress = (totalSent * 100 / file.length()).toInt()
                    Timber.i("发送进度：$progress%")
                    conn.send(chunk)
//                    newBean = DownloadFileBean()
//                    newBean.childCmd = "fileProgress"
//                    newBean.fileProgress = progress
//                    conn.send(JsonUtil.anyToJson(newBean))
                }
            }

            newBean = DownloadFileBean()
            newBean.childCmd = "fileEnd"
            newBean.cmd = bean.cmd
            conn.send(JsonUtil.anyToJson(newBean))
        } catch (e: IOException) {
            newBean = DownloadFileBean()
            newBean.cmd = bean.cmd
            newBean.errorReason = "ERROR: ${e.message}"
            conn.send(JsonUtil.anyToJson(newBean))
        }
    }
}
